using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GoChat_for_Windows.Models;
using GoChat_for_Windows.Services;
using GoChat_for_Windows.Views;

namespace GoChat_for_Windows.ViewModels
{
    public partial class MainViewModel : ViewModelBase
    {
        private readonly INavigationService _navigationService;
        private readonly ILocalStorageService _localStorageService;
        private readonly UdpService _udpService;
        private readonly Microsoft.UI.Dispatching.DispatcherQueue _dispatcherQueue;

        [ObservableProperty]
        private User? currentUser;

        [ObservableProperty]
        private ObservableCollection<User> userList = new();

        [ObservableProperty]
        private User? selectedUser;

        [ObservableProperty]
        private bool isConnected;

        public MainViewModel(
            IApiService apiService,
            INavigationService navigationService,
            ILocalStorageService localStorageService,
            UdpService udpService) : base(apiService)
        {
            _navigationService = navigationService;
            _localStorageService = localStorageService;
            _udpService = udpService;
            _dispatcherQueue = Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread();

            // 订阅UDP连接状态变化
            _udpService.ConnectionStatusChanged += (s, connected) =>
            {
                _dispatcherQueue.TryEnqueue(() =>
                {
                    IsConnected = connected;
                    if (!connected)
                    {
                        ErrorMessage = "UDP连接已断开,正在尝试重新连接...";
                        // 尝试重新连接
                        _ = ReconnectAsync();
                    }
                    else
                    {
                        ClearError();
                    }
                });
            };

            // 订阅消息接收
            _udpService.MessageReceived += (s, message) =>
            {
                _dispatcherQueue.TryEnqueue(() =>
                {
                    // 处理收到的消息
                    HandleReceivedMessage(message);
                });
            };
        }

        private async Task ReconnectAsync()
        {
            try
            {
                if (CurrentUser != null)
                {
                    await _udpService.StartAsync(CurrentUser);
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = "重新连接失败: " + ex.Message;
            }
        }

        private void HandleReceivedMessage(Message message)
        {
            try
            {
                // 根据消息类型处理
                switch (message.MessageType)
                {
                    case MessageType.Heartbeat:
                        // 收到心跳消息,发送回执
                        var ack = new Message
                        {
                            SenderId = CurrentUser?.Id ?? 0,
                            ReceiverId = message.SenderId,
                            MessageType = MessageType.HeartbeatAck,
                            SendTime = DateTime.Now
                        };
                        _ = _udpService.SendMessageAsync(ack);
                        break;

                    case MessageType.HeartbeatAck:
                        // 收到心跳回执,更新连接状态
                        IsConnected = true;
                        break;

                    default:
                        // 其他消息类型由ChatViewModel处理
                        break;
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = "处理消息失败: " + ex.Message;
            }
        }

        public async Task InitializeAsync()
        {
            try
            {
                IsBusy = true;
                ClearError();

                // 加载当前用户信息
                CurrentUser = await _localStorageService.GetUserAsync();
                if (CurrentUser == null)
                {
                    // 如果没有用户信息,返回登录页
                    _navigationService.Navigate(typeof(LoginPage));
                    return;
                }

                // 加载用户列表
                await LoadUserListAsync();

                // 启动UDP服务
                await _udpService.StartAsync(CurrentUser);
            }
            catch (Exception ex)
            {
                ErrorMessage = "初始化失败: " + ex.Message;
            }
            finally
            {
                IsBusy = false;
            }
        }

        private async Task LoadUserListAsync()
        {
            try
            {
                var users = await ApiService.GetUserListAsync();
                _dispatcherQueue.TryEnqueue(() =>
                {
                    UserList.Clear();
                    foreach (var user in users)
                    {
                        if (CurrentUser != null && user.Id != CurrentUser.Id) // 不显示自己
                        {
                            UserList.Add(user);
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                ErrorMessage = "加载用户列表失败: " + ex.Message;
            }
        }

        [RelayCommand]
        private async Task RefreshUserListAsync()
        {
            await LoadUserListAsync();
        }

        [RelayCommand]
        private async Task StartChatAsync(User user)
        {
            if (user != null)
            {
                _navigationService.Navigate(typeof(ChatPage), user);
            }
        }

        [RelayCommand]
        private async Task LogoutAsync()
        {
            try
            {
                // 停止UDP服务
                _udpService.Stop();
                
                // 清除用户数据
                await _localStorageService.ClearUserAsync();
                await _localStorageService.ClearTokenAsync();
                
                // 最后导航到登录页
                _navigationService.Navigate(typeof(LoginPage));
            }
            catch (Exception ex)
            {
                ErrorMessage = "退出登录失败: " + ex.Message;
            }
        }
    }
} 